import { constantRouterMap } from '@/router/index'
// import { getAllMenus } from '@/api/login'
/**
 * 通过authority判断是否与当前用户权限匹配
 * @param menus
 * @param route
 */
// function hasPermission(menus, route) {
//   if (route.meta && route.meta.roles) {
//     if (menus[route.name]) {
//       return 'auth'
//     }
//   } else {
//     return 'free'
//   }
// }

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */

// function filterAsyncRouter(asyncRouterMap, menus, menuDatas) {
//   let accessedRouters = asyncRouterMap.map(route => {
//     if (hasPermission(menus, route) === 'auth') {
//       route.meta.title = (menuDatas[route.name] || {}).title
//       route.meta.icon = (menuDatas[route.name] || {}).icon
//       if (route.children && route.children.length) {
//         route.children = filterAsyncRouter(route.children, menus, menuDatas)
//       }
//       return route
//     } else if (hasPermission(menus, route) === 'free') {
//       if (route.children && route.children.length) {
//         route.children = filterAsyncRouter(route.children, menus, menuDatas)
//       }
//       return route
//     }
//   })
//   accessedRouters = accessedRouters.filter(v => v)
//   return accessedRouters
// }

// 获取白名单
const whiteList1 = constantRouterMap.map((route) => {
  if (route.meta && !route.meta.roles) {
    return route.path
  }
})
const whiteList2 = whiteList1.filter((v) => v)

const state = {
  whiteList: whiteList2,
  routers: constantRouterMap,
  addRouters: [],
  includeList: [] // keep-alive需要缓存的组件的组件名
}

const mutations = {
  SET_ROUTERS: (state, routers) => {
    state.addRouters = routers
    state.routers = constantRouterMap.concat(routers)
  },
  SET_INCLUDELIST: (state, includeList) => {
    state.includeList = includeList
  }
}

const actions = {
  // generateRoutes({ commit }, menus) {
  //   return new Promise(resolve => {
  //     getAllMenus().then(data => {
  //       const menuDatas = {}
  //       for (let i = 0; i < data.length; i++) {
  //         menuDatas[data[i].code] = data[i]
  //       }
  //       const accessedRouters = filterAsyncRouter(asyncRouterMap, menus, menuDatas)
  //       commit('SET_ROUTERS', accessedRouters)
  //       resolve()
  //     })
  //   })
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
